package com.dianwoba.universe.redis;

import com.dianwoba.universe.cache.JedisTemplate;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import redis.clients.jedis.ShardedJedis;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 缓存操作
 */
public class ShardedCacheService {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	private JedisTemplate<String, Object, ShardedJedis> jedisTemplate;

	/*
	 * 缓存最大过期时间-一个月
	 */
	public static final int EXPIRE_TIME_MAX = 30 * 24 * 3600;

	/*
	 * 缓存过期时间-半天
	 */
	public static final int EXPIRE_TIME_HALFDAY = 12 * 3600;

	/*
	 * 缓存过期时间-整天
	 */
	public static final int EXPIRE_TIME_ONEDAY = 24 * 3600;

	/******************************
	 ********* 缓存操作 ***********
	 ******************************/

	/**
	 * 设置缓存
	 * 
	 * @param key
	 * @param value
	 */
	public void putCache(String key, Object value) {
		try {
			jedisTemplate.opsForValue().set(key, value);
		} catch (Exception e) {
			logger.error("PUT cache exception [key=" + key + ", value=" + value + "].", e);
		}
	}

	/**
	 * 设置缓存，并设定缓存时长（秒）
	 * 
	 * @param key
	 * @param value
	 * @param expire
	 */
	public void putCache(String key, Object value, int expire) {
		try {
			jedisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
		} catch (Exception e) {
			logger.error("PUT cache exception [key=" + key + ", value=" + value + ", expire=" + expire + "].", e);
		}
	}

    public Long putIfAbsent(String key, Object value) {
        try {
            return jedisTemplate.opsForValue().setIfAbsent(key, value);
        } catch (Exception e) {
            logger.error("putIfAbsent cache exception [key=" + key + ", value=" + value +"].", e);
        }
        return null;
    }

	/**
	 * 获取缓存数据
	 * 
	 * @param key
	 * @return
	 */
	public Object getCache(String key) {
		try {
			return jedisTemplate.opsForValue().get(key);
		} catch (Exception e) {
			logger.error("GET cache exception [key=" + key + "].", e);
		}
		return null;
	}
	
	
	/**
	 * 获取缓存数据
	 * 
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getCache(String key, Class<T> clazz) {
		try {
			return (T)jedisTemplate.opsForValue().get(key, clazz);
		} catch (Exception e) {
			logger.error("GET cache exception [key=" + key + "].", e);
		}
		return null;
	}

    public <T> T getCache(String key, TypeReference<T> typeReference) {
        try {
            return (T) jedisTemplate.opsForValue().get(key, typeReference);
        } catch (Exception e) {
            logger.error("GET cache exception [key=" + key + "].", e);
        }
        return null;
    }

	/**
	 * 删除缓存
	 * 
	 * @param key
	 */
	public void removeCache(String key) {
		try {
			jedisTemplate.delete(key);
		} catch (Exception e) {
			logger.error("Remove cache exception [key=" + key + "].", e);
		}
	}

	/******************************
	 ********* 队列操作 ***********
	 ******************************/

	/**
	 * 队列缓存设置
	 * 
	 * @param key
	 * @param value
	 */
	public void putQueue(String key, Object value) {
		try {
			jedisTemplate.opsForList().leftPush(key, value);
		} catch (Exception e) {
			logger.error("PUT Queue cache exception [key=" + key + ", value=" + value + "].", e);
		}
	}

	/**
	 * 获取队列缓存
	 * 
	 * @param key
	 * @return
	 */
	public Object getQueue(String key) {
		try {
			return jedisTemplate.opsForList().rightPop(key);
		} catch (Exception e) {
			logger.error("GET Queue cache exception [key=" + key + "].", e);
		}
		return null;
	}

    public <T> T getQueue(String key, Class clazz) {
        try {
            return (T) jedisTemplate.opsForList().rightPop(key, clazz);
        } catch (Exception e) {
            logger.error("GET Queue cache exception [key=" + key + "].", e);
        }
        return null;
    }

    public <T> List<T> range(String key, long start, long end, Class clazz) {
        try {
            return (List<T>) jedisTemplate.opsForList().range(key, start, end, clazz);
        } catch (Exception e) {
            logger.error("GET Queue cache exception [key=" + key + "].", e);
        }
        return null;
    }

    public <T> T head(String key) {
        List<Object> objects = null;
        try {
            objects = jedisTemplate.opsForList().range(key, 0, 1);
        } catch (Throwable e) {
            logger.error("get head from cache exception [key=" + key + "].", e);
            return null;
        }
        return objects != null && objects.size() != 0 ? (T) objects.get(0) : null;
    }

	/******************************
	 ********* 栈操作 ***********
	 ******************************/
	public void putStack(String key, Object value) {
		try {
			jedisTemplate.opsForList().leftPush(key, value);
		} catch (Exception e) {
			logger.error("PUT Stack cache exception [key=" + key + ", value=" + value + "].", e);
		}
	}

	public Object getStack(String key) {
		try {
			return jedisTemplate.opsForList().leftPop(key);
		} catch (Exception e) {
			logger.error("GET Stack cache exception [key=" + key + "].", e);
		}
		return null;
	}

	public int length(String key) {
		try {
			return jedisTemplate.opsForList().size(key).intValue();
		} catch (Exception e) {
			logger.error("GET cache length exception [key=" + key + "].", e);
		}
	    return 0;
	}

	public void expire(String key, long timeout, TimeUnit unit) {
		try {
			jedisTemplate.expire(key, timeout, unit);
		} catch (Exception e) {
			logger.error("SET expire time exception [key=" + key + "].", e);
		}
	}

	/******************************
	 ********* hash操作 ***********
	 ******************************/
	/**
	 * hash put all
	 * 
	 * @param key
	 * @param map
	 * @author Het.C
	 * @date 2015年10月12日
	 */
	public void hputs(String key, HashMap<? extends Object, ? extends Object> map) {
		try {
			jedisTemplate.opsForHash().putAll(key, map);
		} catch (Exception e) {
			logger.error("PUT All Hash exception [key=" + key + "].", e);
		}
	}

	/**
	 * hash put
	 * 
	 * @param key
	 * @param hashKey
	 * @param value
	 * @author Het.C
	 * @date 2015年10月12日
	 */
	public void hput(String key, Object hashKey, Object value) {
		try {
			jedisTemplate.opsForHash().put(key, hashKey, value);
		} catch (Exception e) {
			logger.error("PUT Hash exception [key=" + key + "].", e);
		}
	}

	/**
	 * hash get
	 * 
	 * @param key
	 * @param hashKey
	 * @return
	 * @author Het.C
	 * @date 2015年10月12日
	 */
	public Object hget(String key, Object hashKey) {
		try {
			return jedisTemplate.opsForHash().get(key, hashKey);
		} catch (Exception e) {
			logger.error("GET Hash exception [key=" + key + "].", e);
		}
		return null;
	}

	/**
	 * hash remove
	 * 
	 * @param key
	 * @param hashKey
	 * @author Het.C
	 * @date 2015年10月12日
	 */
	public void hrem(String key, Object hashKey) {
		try {
			jedisTemplate.opsForHash().delete(key, hashKey);
		} catch (Exception e) {
			logger.error("DELETE Hash exception [key=" + key + "].", e);
		}
	}

	/**
	 * hash size
	 * 
	 * @param key
	 * @return
	 * @author Het.C
	 * @date 2015年10月12日
	 */
	public long hsize(String key) {
		try {
			return jedisTemplate.opsForHash().size(key);
		} catch (Exception e) {
			logger.error("GET Hash size exception [key=" + key + "].", e);
		}
		return 0;
	}

	/**
	 * hash keys
	 * 
	 * @param key
	 * @return
	 * @author Het.C
	 * @date 2015年10月12日
	 */
	public Set<?> hkeys(String key) {
		try {
			return jedisTemplate.opsForHash().keys(key);
		} catch (Exception e) {
			logger.error("GET Hash size exception [key=" + key + "].", e);
			return null;
		}
	}

	/**
	 * hash keys
	 * 
	 * @param key
	 * @return
	 * @author Het.C
	 * @date 2015年10月12日
	 */
	public List<Object> hvals(String key) {
		try {
			return jedisTemplate.opsForHash().values(key);
		} catch (Exception e) {
			logger.error("GET Hash size exception [key=" + key + "].", e);
			return null;
		}
	}

	/**
	 * 取出Map
	 */
	public Map<Object, Object> hMap(String key) {
		try {
			return jedisTemplate.opsForHash().entries(key);
		} catch (Exception e) {
			logger.error("GET Map size exception [key=" + key + "].", e);
			return null;
		}
	}

	/**
	 * 查询该hashKey对应的field是否存在
	 */
	public boolean hexists(String key, Object hashKey) {
		try {
			return jedisTemplate.opsForHash().hasKey(key, hashKey);
		} catch (Exception e) {
			logger.error("GET Map size exception [key=" + key + "].", e);
			return false;
		}
	}

    public boolean exists(String key){
        try {
            return jedisTemplate.opsForValue().exists(key);
        }catch (Throwable e){
            logger.error("exists exception [key=" + key + "].", e);
            return false;
        }
    }
	
	/******************************
	 ********* set操作 ***********
	 ******************************/
	/**
	 * set add
	 * 
	 * @param key
	 * @param values
	 */
	public void sadd(String key, Object... values) {
		try {
			jedisTemplate.opsForSet().add(key, values);
		} catch (Exception e) {
			logger.error("Add set exception [key=" + key + "].", e);
		}
	}
	
	/**
	 * set exist
	 * 
	 * @param key
	 */
	public Long ssize(String key) {
		try {
			return jedisTemplate.opsForSet().size(key);
		} catch (Exception e) {
			logger.error("Get set size exception [key=" + key + "].", e);
			return null;
		}
	}
	
	/**
	 * set get
	 * 
	 * @param key
	 */
	public Set<?> sget(String key) {
		try {
			return jedisTemplate.opsForSet().members(key);
		} catch (Exception e) {
			logger.error("Get set exception [key=" + key + "].", e);
			return null;
		}
	}

    public Set<?> sget(String key,Class clazz){
        try {
            return jedisTemplate.opsForSet().members(key,clazz);
        } catch (Exception e) {
            logger.error("Get set exception [key=" + key + "].", e);
            return null;
        }
    }

	public Long srem(String key, Object... values) {
		try {
			return jedisTemplate.opsForSet().remove(key, values);
		} catch (Throwable e) {
			logger.error("Get set exception [key=" + key + "].", e);
			return null;
		}
	}
	/************************************************************
	 ********************** zset 操作*****************************
	 ************************************************************/
	/**
	 * @author zengdan 往Zset插入数据
	 */
	public void zsetPut(String key, Object hashKey, Double score) {
		try {
			jedisTemplate.opsForZSet().add(key, hashKey, score);
		} catch (Exception e) {
			logger.error("PUT Zset exception [key=" + key + "].", e);
		}
	}

	/**
	 * @author zengdan 查询Zset,按照开始结束score
	 */
	public Set<?> zsetGet(String key, Double arg0, Double arg1) {
		try {
			return jedisTemplate.opsForZSet().rangeByScore(key, arg0, arg1);
		} catch (Exception e) {
			logger.error("GET Zset exception [key=" + key + "].", e);
			return null;
		}
	}

	/**
	 * zset长度
	 */
	public Long zsize(String key){
		try {
			return jedisTemplate.opsForZSet().size(key);
		} catch (Exception e) {
			logger.error("zput exception [key=" + key + "].", e);
			return null;
		}
	}

	/**
	 * 添加Zset中的元素
	 */
	public Long zput(String key, Object value, double score){
		try {
			return jedisTemplate.opsForZSet().add(key, value, score);
		} catch (Exception e) {
			logger.error("GET Zset exception [key=" + key + "].", e);
			return null;
		}
	}
	
	/**
	 * @author chensheng 删除Zset中的元素
	 */
	public Long zrem(String key, Object... values){
		try {
			return jedisTemplate.opsForZSet().remove(key, values);
		} catch (Exception e) {
			logger.error("GET Zset exception [key=" + key + "].", e);
			return null;
		}
	}

	/**
	 * 从Zet获取范围内的值
	 *
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set zrange(String key, long start, long end) {
		try {
			return jedisTemplate.opsForZSet().range(key, start, end);
		} catch (Exception e) {
			logger.error("zrange exception [key=" + key + "].", e);
			return Collections.emptySet();
		}
	}

	/**
	 * 从zset中获取一定范围的值
	 *
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public Set zrangeByScore(String key, double min, double max) {
		try {
			return jedisTemplate.opsForZSet().rangeByScore(key, min, max);
		} catch (Exception e) {
			logger.error("zrangeByScore exception [key=" + key + "].", e);
			return Collections.emptySet();
		}
	}

	/**
	 * 模糊查询
	 */
	public Set<String> fuzzyQuery(String pattern) {
		throw new UnsupportedOperationException("method Unsupported.");
	}

	/************************************************************
	 ****************** distribute lock **********************
	 ************************************************************/
	/**
	 * lock
	 * 
	 * @param key
	 * @return
	 */
	public boolean acquireDistributeLock(final String key, String version) {
		throw new UnsupportedOperationException("method Unsupported.");
	}

	/**
	 * release lock
	 * 
	 * @param key
	 */
	public void releaseDistributeLock(String key) {
		throw new UnsupportedOperationException("method Unsupported.");
	}

	public Long increment(String key, Long delta) {
		if (jedisTemplate.getValueSerializer() instanceof JdkSerializationRedisSerializer) {
			logger.error("serializer unsupported: method unsupported JdkSerializationRedisSerializer.");
			throw new UnsupportedOperationException("serializer unsupported: method unsupported JdkSerializationRedisSerializer.");
		}
		
		try {
			return jedisTemplate.opsForValue().increment(key, delta);
			
		} catch (Exception e) {
			logger.error("increment cache exception [key=" + key + ", delta=" + delta + "].", e);
		}
		return null;
	}

	public void setCache(String key, String value) {
		try {
			jedisTemplate.opsForValue().set(key, value);
		} catch (Exception e) {
			logger.error("setCache cache exception [key=" + key + ", value=" + value + "].", e);
		}
	}

	public List<String> get(List<String> keys) {
		throw new UnsupportedOperationException("method unsupported.");
	}

	public JedisTemplate<String, Object, ShardedJedis> getJedisTemplate() {
		return jedisTemplate;
	}

	public void setJedisTemplate(JedisTemplate<String, Object, ShardedJedis> jedisTemplate) {
		this.jedisTemplate = jedisTemplate;
	}
}
